<script lang="ts" setup>

import { UserInfoAddDto, UserProductRelationDto } from '@/models/dtos/adminUser/userinfo/UserInfoAddDto';
import { inject, nextTick, onMounted, reactive, ref, Ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { sexOption, statusOption } from '@/models/enums/EnumOptions';
import { PickerOption, pickerProps, showConfirmDialog, showSuccessToast, showToast } from 'vant';
import { listSearchProduct } from '@/api/product/ProductApi';
import { ProductListVo } from '@/models/vos/product/ProductListVo';
import { getUserInfo, addUserInfo, updateUseInfo } from '@/api/userInfo/UserInfoApi';
import { formatTimestamp } from '@/utils/format';

const router = useRouter();
const route = useRoute();
let id = route.query.id?.toString() ?? "";

var showNavbar = inject("showNavbar") as Ref<boolean>;
showNavbar.value = false;

const userAddForm = ref<any>();

const historyBack = () => {
    router.push({ path: "/user/list" });
};

const formDto = ref<UserInfoAddDto>(new UserInfoAddDto())
const toAddUser = async () => {
    userAddForm.value.validate().then(() => {
        if (id) {
            updateUseInfo(id, formDto.value).then(() => {
                showToast("开通成功")
                setTimeout(()=>{
                    historyBack();
                },1000);
            }).catch(resp => {
                const { code, msg, data } = resp.data;
                showToast(msg);
            });
        }
        else {
            addUserInfo(formDto.value).then(() => {
                showToast("开通成功");
                setTimeout(()=>{
                    historyBack();
                },1000);
            }).catch(resp => {
                const { code, msg, data } = resp.data;
                showToast(msg);
            });
        }

    }).catch(() => {
        showToast("表单校验失败，请检查")
    });


};

var productRelationDto = ref(new UserProductRelationDto());

const addProductDialog = () => {
    productRelationDto.value = new UserProductRelationDto();
    formDto.value.products.push(new UserProductRelationDto());
    nextTick(() => {
        activeItemIndex.value = (formDto.value.products.length - 1).toString();
    })

};

let productPickerOption = ref<PickerOption[]>([]);
let productList: ProductListVo[] = [];
const getPickerOption = async () => {
    productList = await listSearchProduct({ keyword: '' });
    productPickerOption.value = productList.map(it => {
        return {
            text: it.productName,
            value: it.id
        };
    })
};
const showProductPicker = () => {
    let selectValues = formDto.value.products.map(it => it.productId);
    productPickerOption.value = productList.filter(it => selectValues.indexOf(it.id) < 0).map(it => {
        return {
            text: it.productName,
            value: it.id
        };
    });
    showSelectProductActionSheet.value = true;
};
const productPickerConfirm = ({ selectedOptions }: { selectedOptions: any }) => {
    let itemIndex = parseInt(activeItemIndex.value);
    if (selectedOptions && selectedOptions.length > 0 && !isNaN(itemIndex)) {
        var id = selectedOptions[0].value;

        let option = productList.filter(it => it.id == id);
        if (option && option.length > 0) {
            formDto.value.products[itemIndex].productId = option[0].id;
            formDto.value.products[itemIndex].productName = option[0].productName;
        }
    }
    showSelectProductActionSheet.value = false;
};

onMounted(async () => {
    await getPickerOption();
    if (id) {
        formDto.value = await getUserInfo(id);
    }
});
const activeItemIndex = ref('');
const showSelectProductActionSheet = ref(false);
const showSelectDatePickerActionSheet = ref(false);
const dateSelectValue = ref<string[]>([]);

let selectAll = false;
const showSelectDatePicker = (isAll: boolean) => {
    selectAll = isAll;
    let date = new Date();
    let selectDateValues = [date.getFullYear().toString(), (date.getMonth() + 1).toString(), date.getDate().toString()];
    dateSelectValue.value = selectDateValues;
    showSelectDatePickerActionSheet.value = true;
};
const itemDatePickerConfirm = ({ selectedValues }: { selectedValues: any }) => {
    dateSelectValue.value = selectedValues;
    let date = (new Date(selectedValues.join('-')).valueOf() / 1000).toString();
    if (selectAll) {
        formDto.value.products = productList.map(it => {
            var vo = new UserProductRelationDto();
            vo.productId = it.id;
            vo.productName = it.productName;
            vo.validTime = date;
            return vo;
        });
    }
    else {
        let itemIndex = parseInt(activeItemIndex.value);
        if (!isNaN(itemIndex)) {

            formDto.value.products[itemIndex].validTime = date;
        }
    }

    showSelectDatePickerActionSheet.value = false;
}
const removeProductItem = (idx: number) => {
    showConfirmDialog({
        title: '确认删除吗？',
        message: '确认删除。',
        width: "90%"
    })
        .then(() => {
            // on confirm
            formDto.value.products.splice(idx, 1);
        })
        .catch(() => {
            // on cancel
        });
};
</script>

<template>
    <van-nav-bar left-text="返回" right-text="保存" title="添加用户" left-arrow @click-left="historyBack"
        @click-right="toAddUser" />
    <van-form name="userForm" ref="userAddForm">
        <van-cell-group inset title="基本信息">
            <van-field v-model="formDto.userName" name="用户名" label="用户名" placeholder="用户名"
                :rules="[{ required: true, message: '请填写用户名' }]" />
            <van-field v-model="formDto.password" name="密码" label="密码" placeholder="密码"
                :rules="[{ required: true, message: '请填写密码' }]" />
            <van-field name="status" label="状态">
                <template #input>
                    <van-radio-group v-model="formDto.status" direction="horizontal" shape="square">
                        <van-radio :name="item.value" v-for="item in statusOption">{{ item.text }}</van-radio>
                    </van-radio-group>
                </template>
            </van-field>
        </van-cell-group>

        <van-cell-group inset>
            <template #title>
                <van-row justify="space-between">
                    <van-col :span="12" style="text-align: left;">开通产品</van-col>
                    <van-col :span="12" style="text-align: right;">
                        <van-icon name="add-o" size="25" @click.stop="addProductDialog" />
                        <van-icon name="passed" size="25" style="margin-left: 10px;"
                            @click.stop="showSelectDatePicker(true)" />
                    </van-col>
                </van-row>
            </template>
            <van-collapse accordion v-model="activeItemIndex">
                <van-collapse-item v-for="(item, idx) in formDto.products" class="product-item" :name="idx">
                    <template #title>
                        <van-row>
                            <van-col :span="10">{{ item.productName }}</van-col>
                            <van-col :span="10">{{ formatTimestamp(item.validTime) }}</van-col>
                            <van-col :span="4" style="text-align: right;">
                                <van-icon name="delete-o" size="20" @click.stop="removeProductItem(idx)" />
                            </van-col>
                        </van-row>
                    </template>
                    <van-cell-group>
                        <van-field v-model="item.productName" is-link readonly name="picker" label="选择产品"
                            placeholder="请选择产品" @click="showProductPicker" />
                        <van-field :model-value="formatTimestamp(item.validTime)" is-link readonly name="datePicker"
                            label="有效时间" placeholder="点击选择时间" @click="showSelectDatePicker(false)" />
                    </van-cell-group>
                </van-collapse-item>
            </van-collapse>

        </van-cell-group>
    </van-form>

    <van-popup v-model:show="showSelectProductActionSheet" position="bottom">
        <van-picker :columns="productPickerOption" @confirm="productPickerConfirm"
            @cancel="showSelectProductActionSheet = false" />
    </van-popup>
    <van-popup v-model:show="showSelectDatePickerActionSheet" position="bottom">
        <van-date-picker v-model="dateSelectValue" @confirm="itemDatePickerConfirm"
            @cancel="showSelectDatePickerActionSheet = false" />
    </van-popup>
</template>
